package main

import (
	"net/http"
	"github.com/micro/go-web"
	"global/core"
	"encoding/json"
	"github.com/ngaut/log"
	"global/libs/http/app"
)

const (
	RequestMethodPost = "POST"
	RequestMethodGet = "GET"
)

type BaseHandler struct {
	request 	*http.Request
	writer 		http.ResponseWriter
}

func (bh *BaseHandler) Error(err app.AppErr) {
	m := app.AppErrorMsg(err)
	bh.Json(m)
}

func (bh *BaseHandler) Json(m interface{}) {
	jsonBytes, err := json.Marshal(m)
	if err != nil {
		log.Fatalf("Error: %s", err)
	}
	bh.writer.Header().Set("Content-Type", "application/json")
	bh.writer.Write(jsonBytes)
}

func (bh *BaseHandler) IsPost() bool {
	return bh.request.Method == RequestMethodPost
}

func (bh *BaseHandler) IsGet() bool {
	return bh.request.Method == RequestMethodGet
}

type Handler struct {
	BaseHandler
	service 		web.Service
	ctx 			*core.Context
}

func NewHandler(
	s web.Service,
	c *core.Context) *Handler {
	return &Handler{
		service: 		s,
		ctx: 			c,
	}
}

func (h *Handler) RegisterHandler(handler string, f func(writer http.ResponseWriter, request *http.Request)) {
	h.service.HandleFunc(handler, func(writer http.ResponseWriter, request *http.Request) {
		h.writer = writer
		h.request = request
		f(writer, request)
	})
}

